//
//  VideoPlayerView.m
//  for_test
//
//  Created by Carlson Lee on 2017/4/6.
//  Copyright © 2017年 Carlson Lee. All rights reserved.
//  播放器

#import "VideoPlayerView.h"
#import <MediaPlayer/MediaPlayer.h>
#import "SDVoiceTipView.h"
#import <AVFoundation/AVFoundation.h>

@interface VideoPlayerView ()<SDVoiceTipViewDelegate>
{
    BOOL _isPlaying;
}

@property(nonatomic, strong)SDVoiceTipView* tipView;

@property(nonatomic, strong)AVPlayerItem* item;
@property(nonatomic, strong)AVPlayerLayer* playerLayer;
@property(nonatomic, readwrite)AVPlayer* player;

@end

@implementation VideoPlayerView

- (instancetype)init
{
    if(self = [super init]){
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(movieToEnd) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(backGroundPauseMoive) name:UIApplicationDidEnterBackgroundNotification object:nil];
    }
    return self;
}

- (SDVoiceTipView *)tipView
{
    if(!_tipView){
        _tipView = [[SDVoiceTipView alloc]initWithType:TIP_TYPE_IMG_STR direction:TIP_DERECTION_VER font:SDFont(16, FONT_TYPE_REGULAR)];
        [self addSubview:_tipView];
        [_tipView.tipLab setTextColor:UIColorFromRGB(0xffffff)];
        _tipView.imgStr = @"voice_over";
        _tipView.tipStr = @"再听一遍";
        _tipView.delegate = self;
    }
    return _tipView;
}

- (void)loadWithPath:(NSString* )path
{
    if(!_item){
        _item = [[AVPlayerItem alloc]initWithURL:[NSURL fileURLWithPath:path]];
        self.player = [[AVPlayer alloc]initWithPlayerItem:_item];
    }
    self.playerLayer = [AVPlayerLayer playerLayerWithPlayer:_player];
    self.playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    [self.layer insertSublayer:self.playerLayer below:self.tipView.layer];
    self.player.volume = 1.0f;
}

- (void)startPlay:(BOOL )isPlay
{
    if(isPlay){
        [self.player play];
    }else{
        [self.player pause];
    }
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    self.playerLayer.frame = self.bounds;
    self.tipView.frame = self.bounds;
}

#pragma mark-----------SDVoiceTipViewDelegate

- (void)sdVoiceTipViewSelect
{
    if(self.player.timeControlStatus == AVPlayerTimeControlStatusPlaying){
        [self.player pause];
    }else{
        [self.player play];
        [self.tipView setAlpha:0.0];
    }
}

#pragma mark------------NSNotification

- (void)movieToEnd
{
    [self.tipView setAlpha:1.0];
    [self.player seekToTime:kCMTimeZero];
}

- (void)backGroundPauseMoive
{
    
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
